﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CloudTaobao.Util;
using System.Runtime.Serialization.Json;
using System.Text;

namespace CloudTaobao
{
    public partial class LoginPage : PhoneApplicationPage
    {
        public loginInfo login = new loginInfo();
        public SessionInfo session = new SessionInfo();

        public LoginPage()
        {
            InitializeComponent();
        }

        private void HandleLoginResponse(IAsyncResult asyncResult)
        {
            try
            {
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                byte[] tmp = new byte[streamResult.Length];
                streamResult.Read(tmp, 0, tmp.Length);
                string result = "";
                for (int i = 0; i != tmp.Length; i++)
                {
                    char tmpChar = (char)tmp[i];
                    result += tmpChar;
                }
                MemoryStream jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(result));
                DataContractJsonSerializer jsonPaser = new DataContractJsonSerializer(typeof(loginInfo));
                login = jsonPaser.ReadObject(jsonStream) as loginInfo;

                if (login.ret.ElementAt(0).Contains("NOT_FOUND_APP"))
                {
                    MessageBox.Show("获得登录Url失败:NOT_FOUND_APP");
                    return;
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    web.Source = new Uri(login.data.url);

                });

            }
            catch (Exception) 
            {
                MessageBox.Show("获得登录Url失败");
                return;
            }
        }

        private void web_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            loading.IsIndeterminate = false;
            loading.Visibility = Visibility.Collapsed;
            if (e.Uri.AbsolutePath.Equals("/mtop/bind_app_result.htm"))
            {
                /*
                string query = HttpUtility.UrlDecode(e.Uri.Query);
                string noPreQuery = query.Substring(1, query.Length-1);
                IDictionary<string, string> parameters = new Dictionary<string, string>();
                string[] pairs = noPreQuery.Split(new char[]{'&'});
                foreach(string pair in pairs){
                    string[] splitedPair = pair.Split(new char[] { '=' });
                    parameters.Add(splitedPair[0], splitedPair[1]);
                }
                return;
                 * */
                try
                {
                    LoginClient client = new LoginClient();
                    client.addParameter("api", "com.taobao.client.mtop.getUserSessionKey");
                    client.addParameter("data", "{\"key\":\"" + login.data.key + "\",\"appkey\":\"12258862\"}");
                    client.addParameter("key", login.data.key);
                    client.addParameter("t", DateTime.Now.ToString());
                    client.sendRequest(new AsyncCallback(HandleGetSessionResponse));

                    loading.IsIndeterminate = true;
                    loading.Visibility = Visibility.Visible;
                    //e.Cancel = true;
                    //AppSettings settings = new AppSettings();
                    //web.Source = new Uri("http://m.taobao.com/syscheck.htm?ttid=400000_12258862@yqft_windowsphone7_1.0.0&imei=" + settings.imei + "&imsi=" + settings.imsi + "&clt_act=startup");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void HandleGetSessionResponse(IAsyncResult asyncResult)
        {
            try
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    loading.IsIndeterminate = false;
                    loading.Visibility = Visibility.Collapsed;
                });
                
                // get the state information
                UpdateState state = (UpdateState)asyncResult.AsyncState;
                HttpWebRequest request = (HttpWebRequest)state.AsyncRequest;

                // end the async request
                state.AsyncResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);

                Stream streamResult;
                // get the stream containing the response from the async call
                streamResult = state.AsyncResponse.GetResponseStream();

                byte[] tmp = new byte[streamResult.Length];
                streamResult.Read(tmp, 0, tmp.Length);
                string result = "";
                for (int i = 0; i != tmp.Length; i++)
                {
                    char tmpChar = (char)tmp[i];
                    result += tmpChar;
                }
                MemoryStream jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(result));
                DataContractJsonSerializer jsonPaser = new DataContractJsonSerializer(typeof(SessionInfo));
                session = jsonPaser.ReadObject(jsonStream) as SessionInfo;

                if (session.ret.ElementAt(0).Contains("NOT_FOUND_USER"))
                {
                    MessageBox.Show("登录失败:NOT_FOUND_USER");
                    return;
                }

                AppSettings settings = new AppSettings();
                settings.nick = session.data.nick;
                settings.token = session.data.token;
                settings.top_session = session.data.topsession;
                settings.valid = true;
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        loading.IsIndeterminate = false;
                        loading.Visibility = Visibility.Collapsed;
                        NavigationService.Navigate(new Uri("/MainFunctionPage.xaml", UriKind.Relative));
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("跳转到主界面错误:" + e.Message);
                    }
                });

            }
            catch (Exception)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("登录失败");
                });
                return;
            }
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoginClient client = new LoginClient();
                client.addParameter("api", "com.taobao.wireless.mtop.getLoginUrl");
                client.addParameter("data", "{\"appkey\":\"12258862\"}");
                client.addParameter("t", DateTime.Now.ToString());
                client.sendRequest(new AsyncCallback(HandleLoginResponse));

                loading.IsIndeterminate = true;
                loading.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }


    public class loginInfo
    {
        public string api;
        public string v;
        public List<string> ret;
        public loginDateInfo data;
        public loginInfo()
        {
            api = "";
            v = "";
            ret = new List<string>();
            data = new loginDateInfo();
        }
    }

    public class loginDateInfo
    {
        public string key;
        public string url;
        public loginDateInfo()
        {
            key = "";
            url = "";
        }
    }

    public class SessionInfo
    {
        public string api;
        public string v;
        public List<string> ret;
        public sessionDateInfo data;
        public SessionInfo()
        {
            api = "";
            v = "";
            ret = new List<string>();
            data = new sessionDateInfo();
        }
    }

    public class sessionDateInfo
    {
        public string topsession;
        public string sid;
        public string time;
        public string ecode;
        public string nick;
        public string token;
        public sessionDateInfo()
        {
            topsession = "";
            sid = "";
            time = "";
            ecode = "";
            nick = "";
            token = "";
        }
    }
}